﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using AsyncSocketServer;

namespace WebServer
{
    // State object for reading client data asynchronously
    public class StateObject : BaseSocketProtocol
    {
        // Client  socket.
        public Socket clientSocket = null;
        // Size of receive buffer.
        public const int BufferSize = 1024 * 6;
        // Receive buffer.
        public byte[] bBuffer = new byte[BufferSize];
        // Received data string.
        public StringBuilder sbContent = new StringBuilder();
    }

    public class Client : StateObject
    {
        private HttpResponseCore httpEntity;
        private Encoding charEncoder = Encoding.UTF8;
        private Tools tool;
        public Dictionary<string, httpEventHandler> KeyHtm;
        private Busness.business bs;
        public string HtmlContent;
        public int CurrentStep;
        static object lock_object = new object();
        static object lock_return = new object();

        public Client() { }

        public Client(HttpResponseCore http)
        {
            httpEntity = http;
            KeyHtm = new Dictionary<string, httpEventHandler>();
            KeyHtm["get_new_randomstring.htm"] = this.CreateNewRandomString;
            //keyHtm["getMicrolientFile.htm"] = this.GetFile;
            KeyHtm["analysis_loginchar.htm"] = this.GetUserUrl;
            KeyHtm["get_user_login_data.htm"] = this.GetUserLoginData;
            KeyHtm["get_user_plugin_data.htm"] = this.GetUserPluginData;
            KeyHtm["get_plugin_data_number.htm"] = this.GetPluginDataNumber;
            bs = new Busness.business();
            tool = new Tools();
        }

        protected string GetPluginDataNumber(params string[] param)
        {
            lock (lock_return)
            {
                for (int i = 1; i <= ServerMainLogic.GetServer().MaxStep; i++)
                {
                    for (int type = 0; type < 4; type++)
                    {
                        DataAccess.UserPluginData data = new DataAccess.UserPluginData();
                        data.begin_time = tool.GetQueryString(param[0], "begin_time");
                        data.end_time = tool.GetQueryString(param[0], "end_time");
                        data.pid = Convert.ToInt32(tool.GetQueryString(param[0], "pid"));
                        data.sid = tool.GetQueryString(param[0], "sid");
                        data.sender = this;
                        data.step = i;
                        data.type = type;
                        Busness.business.SaveUserPluginDataToList(DataAccess.eDataBaseCommand.edbcmd_GetPluginStepNumber, data);                       
                    }
                }

                //ServerMainLogic.GetServer().WriteLog("请求插件统计步骤:sid :" + data.sid + " ; pid: " + data.pid + "; type: " + data.type + " ; begin_time: " + data.begin_time + " ; end_time: " + data.end_time);
                return "";
            }
        }

        protected string GetUserPluginData(params string[] param)
        {
            DataAccess.UserPluginData data = new DataAccess.UserPluginData();
            data.uid = tool.GetQueryString(param[0], "uid");
            data.puid = data.uid;
            data.sid = tool.GetQueryString(param[0], "sid");
            if (data.sid == "9999" || data.sid == "200" || (Convert.ToInt32(data.sid) >= 100 && Convert.ToInt32(data.sid) <= 301))
            {
                ServerMainLogic.GetServer().WriteLog("内网请求 服务器ID " + data.sid + "用户ID "+ data.uid );
                SendResponse("同步成功", HttpExtension.HTML);
                return "";
            }
            HttpRequest request = new HttpRequest();
            data.pid = Convert.ToInt32(tool.GetQueryString(param[0], "pid"));
            data.step = Convert.ToInt32(tool.GetQueryString(param[0], "step"));
            data.type = Convert.ToInt32(tool.GetQueryString(param[0], "type"));
            string postRet = request.Post(ServerMainLogic.GetServer().RequestUrl , param[0]);
            data.time = Convert.ToString(tool.GetTimeStamp());
            data.otherData =  postRet;
            Busness.business.SaveUserPluginDataToList(DataAccess.eDataBaseCommand.edbcmd_InsertPluginData, data);
            ServerMainLogic.GetServer().WriteLog("插件请求:" + param[0]);
            SendResponse("同步成功", HttpExtension.HTML);
            return "";
        }

        protected string GetUserLoginData(params string[] param)
        {
            string uid = tool.GetQueryString(param[0], "uid");
            if (uid != null && uid != "")
            {
                string reqstr = "game=LCTQ&account=" + uid + "&server=t1";
                AnalySendRequest(reqstr);
                SendResponse("同步成功", HttpExtension.HTML);
            }
            else
            {
                SendResponse("uid 有误", HttpExtension.HTML);
            }
            return "";
        }

        /// <summary>
        /// 生成文件名字，并记录
        /// </summary>
        /// <param name="data"></param>
        /// <param name="param">param[0]:http请求携带的参数，这里是jQuery的 Jason callBack 函数名字
        /// param[1]: 发送请求的页面的href</param>
        /// <returns>返回生成的文件名后缀</returns>
        protected virtual string CreateNewRandomString(params string[] param)
        {
            try
            {
                lock (lock_object)
                {
                    string randomString = tool.Get6RandomChar();
                    while (bs.GetContainsKey(randomString) || ServerMainLogic.GetServer().GetQueueContainsKey(randomString))
                    {
                        randomString = tool.Get6RandomChar();
                        //ServerMainLogic.GetServer().WriteLog("Key重复：Key = " + randomString);
                    }
                    string successCallback = tool.GetJsonCallBackFromUrl(param[0]);
                    string url = param[1];
                    ServerMainLogic.GetServer().WriteKeyUrlQueue(randomString, url, param[1]);
                    System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
                    string jsonCode = successCallback + "({\"key\":\"" + randomString + "\"})";
                    SendResponse(jsonCode, HttpExtension.HTML);
                    ServerMainLogic.GetServer().WriteLog("微端下载请求  生成KEY: " + randomString + "  URL:" + url);
                    return randomString;
                }
            }
            catch 
            {
                ServerMainLogic.GetServer().WriteLog("生成Key 出错：" + tool.GetTimeStamp());
                return "";
            }
        }
        /// <summary>
        /// 微端发送文件名后缀，服务器向微端发送重定向的页面
        /// </summary>
        /// <param name="param">param[0]:微端的文件名后缀</param>
        /// <returns>返回查找到的url</returns>
        protected virtual string GetUserUrl(params string[] param)
        {
            string key = tool.GetQueryString(param[0], "key");
            string url = bs.GetUrlByKey(key);
            string referer = bs.GetRefererByKey(key);
            if (url != "")
            {
                url = url.Replace("web", "mini");
                Redirect(url);
            }
            else
            {
                Redirect(ServerMainLogic.GetServer().GameLoginUrl);
            }
            ServerMainLogic.GetServer().WriteLog("微端登陆请求： 请求Key=" + key);
            if (referer == "")
            {
                return "";
            }
            AnalySendRequest(url);
            return url;
        }

        protected virtual void AnalySendRequest(string referer)
        {
            HttpRequest request = new HttpRequest();
            Platform platform = tool.GetPlatformByReferer(referer);
            if (platform == Platform.PLATFORM_YOUXI)
            {
                // 游戏平台
                request.Post(ServerMainLogic.GetServer().RequestUrl, tool.GetYouxiRequestString(referer));
            }
            else if (platform == Platform.PLATFORM_YY)
            {
                //YY平台
                request.Post(ServerMainLogic.GetServer().RequestUrl, tool.GetYYRequestString(referer));
            }
            else if (platform == Platform.PLATFORM_WAN360)
            {
                //360玩平台
                request.Post(ServerMainLogic.GetServer().RequestUrl, tool.Get360WanRequestString(referer));
            }
        }

        private string GetFile(object data, string param)
        {
            Socket clientSocket = (Socket)data;
            string uid = tool.GetJsonCallBackFromUrl(param);
            string fileName = ServerMainLogic.GetServer().getUserExecName(uid);
            ServerMainLogic.GetServer().GetHttpResponseEntity().SendExeFileToClient(this, fileName);
            return fileName;
        }

        public virtual void SendResponse(string content)
        {
            httpEntity.SendOkResponse(this, charEncoder.GetBytes(content), HttpExtension.HTML);
        }
        public virtual void SendResponse(string content, string contentType)
        {
            httpEntity.SendOkResponse(this, charEncoder.GetBytes(content), contentType);
        }
        public virtual void SendResponse(string content, string responseCode, string contentType)
        {
            httpEntity.SendResponse(this, content, responseCode, contentType);
        }
        public virtual void Redirect(string url)
        {
            httpEntity.Redirect(this, url);
        }
    }
}
